<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-button type="info" style="float: right;margin-top: 5px;margin-right: 2px" round @click="handleBack()">返回</el-button>
      <div style="text-align: center;font-size: xx-large;color: #3b3f48">{{form.title}}</div>
      <!-- 添加点赞按钮 -->
      <div class="like-container">
        <div class="like-button" :class="{ 'liked': isLiked }" @click="handleLike">
          <el-icon><Sugar /></el-icon>
          <span class="like-count">{{ likeCount }}</span>
        </div>
      </div>
      <div class="info-header">
        <template v-if="form.userId">
          <div class="meta-item">
            <span class="label">发布作者：</span>
            <span class="value">
              {{ form.userName || form.nickName || '未知用户' }}
            </span>
          </div>
        </template>

        <template v-if="form.publishTime">
          <div class="meta-item">
            <span class="label">发布时间：</span>
            <span class="value">{{ parseTime(form.publishTime, '{y}-{m}-{d}') }}</span>
          </div>
        </template>

        <template v-if="form.infoType">
          <div class="meta-item">
            <span class="label">资讯类型：</span>
            <dict-tag :options="info_type" :value="form.infoType"/>
          </div>
        </template>
        <template v-if="form.status">
          <div class="meta-item">
            <span class="label">发布状态：</span>
            <dict-tag :options="publish_status" :value="form.status"/>
          </div>
        </template>
      </div>
      <div class="ql-editor" v-html="form.content"></div>

      <!-- 评论区 -->
      <div class="comment-section">
        <h3>评论区</h3>
        <!-- 评论输入框 -->
        <div class="comment-input">
          <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
          />
          <el-button type="primary" @click="submitComment" style="margin-top: 10px">发表评论</el-button>
        </div>

        <!-- 评论列表开始前的调试信息 -->
        <div v-if="isDev" style="margin-bottom: 10px; color: #999; font-size: 12px;">
          评论总数: {{ comments.length }}
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <template v-if="comments.length > 0">
            <CommentItem
                v-for="comment in comments"
                :key="comment.commentId"
                :comment="comment"
                @reply="handleReply"
                @delete="handleDeleteComment"
            />
          </template>
          <div v-else class="no-comment">
            暂无评论
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getInfo } from "@/api/healthSys/info.js"
import { addComment, getCommentList, deleteComment } from "@/api/healthSys/comment.js"
import { addLike, deleteLike, getLikeStatus, getLikeCount } from "@/api/healthSys/like.js"
import useUserStore from '@/store/modules/user'
import CommentItem from './CommentItem.vue'
import {Star, Sugar} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const authorInfo = ref({})
// 添加基础URL
const baseURL = import.meta.env.VITE_APP_BASE_API

// 字典数据
const { info_type, publish_status } = proxy.useDict('info_type', 'publish_status')

// 响应式数据
const form = ref({})
const endangered = ref(null)
const commentContent = ref('')
const comments = ref([])
const userStore = useUserStore()

// 添加这个常量
const isDev = process.env.NODE_ENV === 'development'

// 添加点赞相关的响应式数据
const isLiked = ref(false)
const likeCount = ref(0)

// 方法定义
const reset = () => {
  form.value = {}
}

// 添加 cleanHtml 函数
const cleanHtml = (html) => {
  const doc = new DOMParser().parseFromString(html, 'text/html')
  return doc.body.textContent || ''
}

const getZXInfo = async (id) => {
  try {
    reset()
    const res = await getInfo(id)
    form.value = res.data
    console.log(form.value)
    // 确保 authorInfo 被正确赋值
    authorInfo.value = res.data.authorInfo || {}
  } catch (error) {
    console.error('获取详情失败:', error)
  }
}
const handleReply = async ({ parent, content }) => {
  try {
    const res = await addComment({
      infoId: endangered.value,
      content: content,
      parentId: parent.commentId,
      replyToUserId: parent.userId,
      replyToUsername: parent.username,
      status: '1'
    })

    if (res.code === 200) {
      proxy.$modal.msgSuccess('回复成功')
      getComments(endangered.value)
    }
  } catch (error) {
    proxy.$modal.msgError('回复失败')
  }
}
// 获取评论列表
const getComments = async (infoId) => {
  try {
    console.log('开始获取评论，infoId:', infoId)
    const res = await getCommentList(infoId)
    console.log('评论API返回数据:', res)

    if (res.code === 200) {
      const commentList = Array.isArray(res.rows) ? res.rows : []
      console.log('原始评论列表:', commentList)

      comments.value = buildCommentTree(commentList)
      console.log('构建树后的评论列表:', comments.value)
    } else {
      console.error('获取评论失败:', res.msg)
      proxy.$modal.msgError(res.msg || '获取评论失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    proxy.$modal.msgError('获取评论失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    proxy.$modal.msgError('请输入评论内容')
    return
  }

  try {
    const res = await addComment({
      infoId: endangered.value,
      content: commentContent.value,
      status: '0' // 设置状态为1，表示未发布
    })
    if (res.code === 200) {
      proxy.$modal.msgSuccess('评论成功')
      commentContent.value = ''
      getComments(endangered.value)
    } else {
      proxy.$modal.msgError(res.msg || '评论失败')
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    proxy.$modal.msgError('评论失败')
  }
}



const cancelReply = () => {
  activeReply.value = null
  replyContent.value = ''
}

// 修改构建评论树的方法
const buildCommentTree = (list) => {
  if (!Array.isArray(list)) {
    console.error('构建评论树时收到非数组数据:', list)
    return []
  }

  console.log('当前用户ID:', userStore.id)
  console.log('原始评论数据:', list)

  const commentMap = {}
  const tree = []

  // 处理评论数据，过滤掉已删除的评论
  list.forEach(comment => {
    // 跳过状态为"已删除"的评论
    if (comment.status === '2') {
      return
    }

    const processedComment = {
      ...comment,
      commentId: comment.commentId,
      children: [],
      username: comment.nickName || `用户${comment.userId}`,
      // 添加基础URL到头像路径
      headImg: comment.avatar ? `${baseURL}${comment.avatar}` : '/default-avatar.png',
      sys_user_id: comment.userId,
      // 移除状态显示
      status: undefined
    }
    console.log('处理后的评论:', processedComment)
    commentMap[processedComment.commentId] = processedComment
  })
  // 构建树形结构
  list.forEach(comment => {
    // 跳过状态为"已删除"的评论
    if (comment.status === '2') {
      return
    }

    const processedComment = commentMap[comment.commentId];
    const parentComment = commentMap[comment.parentId];

    if (comment.parentId && parentComment) {
      // 确保直接父评论的用户名被正确绑定
      processedComment.replyToUsername = parentComment.nickName || `用户${parentComment.userId}`;

      if (!parentComment.children) {
        parentComment.children = [];
      }
      parentComment.children.push(processedComment);
    } else {
      tree.push(processedComment);
    }
  })
  // 按时间倒序排序
  tree.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))

  // 对每个评论的子评论也进行时间排序
  tree.forEach(comment => {
    if (comment.children && comment.children.length > 0) {
      comment.children.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    }
  })

  return tree
}

const handleBack = () => {
  router.go(-1)
}

// 修改删除评论的方法
const handleDeleteComment = (comment) => {
  console.log('尝试删除评论:', comment)
  console.log('当前用户ID:', userStore.id)
  console.log('评论作者ID:', comment.sys_user_id)

  // 检查是否是评论作者，使用String()确保类型一致
  if (String(comment.sys_user_id) !== String(userStore.id)) {
    proxy.$modal.msgError('您没有权限删除此评论')
    return
  }

  proxy.$modal.confirm('确定要删除这条评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteComment(comment.commentId)
      if (res.code === 200) {
        proxy.$modal.msgSuccess('删除成功')
        // 重新获取评论列表
        getComments(endangered.value)
      } else {
        proxy.$modal.msgError(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除评论失败:', error)
      proxy.$modal.msgError('删除失败')
    }
  }).catch(() => {
    // 取消删除操作
  })
}

// 添加点赞相关的方法
const handleLike = async () => {
  if (!userStore.id) {
    proxy.$modal.msgError('请先登录')
    return
  }

  try {
    if (isLiked.value) {
      await deleteLike(endangered.value)
      likeCount.value--
    } else {
      await addLike(endangered.value)
      likeCount.value++
    }
    isLiked.value = !isLiked.value
  } catch (error) {
    console.error('点赞操作失败:', error)
    proxy.$modal.msgError('操作失败')
  }
}

// 获取点赞状态和数量
const getLikeInfo = async () => {
  try {
    const [statusRes, countRes] = await Promise.all([
      getLikeStatus(endangered.value),
      getLikeCount(endangered.value)
    ])

    if (statusRes.code === 200) {
      isLiked.value = statusRes.data
    }
    if (countRes.code === 200) {
      likeCount.value = countRes.data
    }
  } catch (error) {
    console.error('获取点赞信息失败:', error)
  }
}

// 生命周期
onMounted(() => {
  console.log('组件挂载，路由参数:', route.query)
  if (route.query.id) {
    endangered.value = route.query.id
    console.log('设置文章ID:', endangered.value)
    getZXInfo(endangered.value)
    getComments(endangered.value)
    getLikeInfo() // 添加获取点赞信息
  } else {
    console.warn('未找到文章ID')
  }
})

</script>

<style lang="scss" scoped>
.info-header {
  margin-bottom: 20px;
  padding: 12px;
  background: #f8f8f8;
  border-radius: 6px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
  min-width: 70px;
  margin-right: 12px;
}

.value {
  color: #333;
}
.circle {
  width: 50px;         /* 容器宽度匹配点击区域 */
  height: 50px;        /* 容器高度匹配点击区域 */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease; /* 添加过渡效果 */

  .img-box {
    width: 40px;       /* 匹配实际图片尺寸 */
    height: 40px;      /* 匹配实际图片尺寸 */
    display: flex;
    justify-content: center;
    align-items: center;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;

    & img {
      width: 100%;     /* 使用百分比自适应容器 */
      height: 100%;    /* 使用百分比自适应容器 */
      object-fit: contain; /* 保持图片比例 */
      transition: transform 0.3s ease; /* 添加图标过渡 */
    }
  }

  /* 点击态效果 */
  &:active {
    transform: scale(0.9);
  }
}

.check {
  /* 移除原阴影动画 */
}

.img-box-check {
  animation: pulse 0.5s ease-in-out;

  img {
    transform: scale(1.1); /* 常驻放大效果 */
  }
}

/* 优化动画关键帧 */
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1.1);
  }
}

.comment-section {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;

  h3 {
    margin-bottom: 20px;
    color: #333;
  }
}

.comment-input {
  margin-bottom: 30px;
}

.comment-list {
  .comment-item {
    padding: 15px 0;
    border-bottom: 1px solid #eee;

    &:last-child {
      border-bottom: none;
    }
  }

  .comment-main {
    margin-bottom: 10px;
  }

  .comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .comment-author {
    font-weight: bold;
    color: #333;
  }

  .comment-time {
    color: #999;
    font-size: 12px;
  }

  .comment-content {
    color: #666;
    line-height: 1.6;
    margin-left: 40px;
  }

  .comment-actions {
    margin-left: 40px;
    margin-top: 8px;
    display: flex;
    gap: 16px;

    .delete-btn {
      color: #f56c6c;

      &:hover {
        color: #f78989;
      }
    }
  }

  .reply-input {
    margin: 10px 0 10px 40px;

    .reply-actions {
      margin-top: 8px;
      text-align: right;

      .el-button {
        margin-left: 10px;
      }
    }
  }

  .reply-list {
    margin-left: 40px;
    background: #f8f8f8;
    border-radius: 4px;
    padding: 10px;

    .reply-item {
      padding: 8px 0;

      &:not(:last-child) {
        border-bottom: 1px solid #eee;
      }

      .comment-content {
        margin-left: 32px;
      }

      .comment-actions {
        margin-left: 32px;
        margin-top: 4px;
      }

      .reply-input {
        margin: 8px 0 8px 32px;
      }

      .user-info {
        display: flex;
        align-items: center;
        gap: 8px;

        .reply-to {
          color: #999;
          font-size: 14px;

          .replied-user {
            color: #409EFF;
            font-weight: 500;
          }
        }
      }
    }
  }

  .no-comment {
    text-align: center;
    color: #999;
    padding: 20px 0;
  }
}
.reply-list {
  border-left: 2px solid #eee;
  margin-top: 8px;
  transition: margin 0.3s ease;

  .comment-item {
    position: relative;
    &::before {
      content: '';
      position: absolute;
      left: -15px;
      top: 20px;
      width: 10px;
      height: 2px;
      background: #eee;
    }
  }
}

.like-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.like-button {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #666;
  transition: all 0.3s ease;
  padding: 8px 16px;
  border-radius: 20px;
  background: #f5f7fa;
  
  &:hover {
    background: #e4e7ed;
  }
  
  .el-icon {
    margin-right: 8px;
    font-size: 20px;
    color: inherit;
  }
  
  .like-count {
    font-size: 16px;
    font-weight: 500;
    color: inherit;
  }
  
  &.liked {
    color: #409EFF;
    background: #ecf5ff;
    
    .el-icon {
      animation: like-animation 0.3s ease;
    }
  }
}

@keyframes like-animation {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.ql-editor {
  :deep(img) {
    max-width: 500px;
    height: 500px;
    display: block;
    margin: 20px auto;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    
    &:hover {
      transform: scale(1.02);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
    }
  }
}
</style>
